<template>
  <div
    class="files-upload-view"
    style="width: 100%; display: flex; flex-wrap: wrap"
  >
    <template v-if="list&&list.length">
      <image-upload-view
        v-for="(item,index) in list"
        :ref="(el) => { setImageRef(el,index)}"
        :key="item.id"
        :data="item"
        :disabled="disabled"
        :is-title="isTitle"
        :is-long="isLong"
        @success="onSuccess"
        @delete="onDelete"
      />
    </template>
    <div
      v-else
      style="width: 100%; display:flex;justify-content:center;"
    >
      <el-empty description="暂无资质" />
    </div>
  </div>
</template>

<script>
import imageUploadView from '../imageUploadView/index.vue'
import {defineComponent, getCurrentInstance, reactive, ref, toRefs, watch,} from 'vue'
import Template from '../comDetailView/template.vue'

export default defineComponent({
  name: 'Index',
  components: { imageUploadView, Template },
  props: {
    list: {
      type: Array,
      default: [],
    },
    isTitle: {
      type: Boolean,
      default: true,
    },
    isLong: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  setup(props) {
    const currentInstance = getCurrentInstance()
    var images = ref([])
    var data = reactive({
      index: 0,
    })

    watch(
      () => props.list,
      (newV, oldV) => {
        if (newV && newV.length) {
          if (!data.index) {
            data.index = newV.length
          }
          for (let i = 0; i < newV.length; i++) {
            if (!newV[i].id) {
              newV[i].id = i + 1
            }
          }
        }
      }
    )

    const validateFiles = () => {
      for (const key in images.value) {
        if (images.value[key]) {
          const str = images.value[key].validateImage()
          if (str) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: str,
            })
            return false
          }
        }
      }

      return true
    }

    const onSuccess = (val) => {
      console.log(val)
      const index = props.list.indexOf(val)
      if (index != -1 && val.name == '其他资质') {
        const a = {
          id: data.index + 1,
          code: '',
          imgName: '',
          isLong: 0,
          isNeed: 0,
          name: '其他资质',
          type: 0,
          url: '',
          validTime: '',
        }
        data.index++
        props.list.splice(index + 1, 0, a)
      }
    }

    const onDelete = (val) => {
      const index = props.list.indexOf(val)
      if (index !== -1 && val.name === '其他资质') {
        props.list.splice(index, 1)
      }
    }

    const setImageRef = (el, index) => {
      images.value[index] = el
    }

    return {
      ...toRefs(data),

      validateFiles,
      setImageRef,
      onSuccess,
      onDelete,
    }
  },
})
</script>

<style scoped>
</style>
